# 在LCNC开机时 给每个绝对值编码器的关节自动发出home命令
# 打开LCNC程序后 2分钟内未开机, 则退出本程序
# 用法: 在ini的[APPLICATIONS]节中加入:
# DELAY = 2
# APP = /usr/bin/python3 auto_home.py

import linuxcnc
import time

try:
	start_time = time.time()
	S = linuxcnc.stat()
	C = linuxcnc.command()
	while True:
		if (time.time() - start_time > 120):
			break
		S.poll()
		inifile = linuxcnc.ini(S.ini_filename)
		if not S.estop and S.enabled:
			for i in range(S.joints):
				encoder_flag = inifile.find(f'JOINT_{i}', 'HOME_ABSOLUTE_ENCODER')
				if int(encoder_flag) == 2 and S.joint[i]['homed'] == 0:
					C.home(i)
			break
except Exception as e:
	print(f"异常: {e}")